package de.tum.in.eist.poll.server;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import de.tum.in.eist.poll.shared.Lecturer;
import de.tum.in.eist.poll.shared.Student;
import de.tum.in.eist.poll.shared.User;

public class UserManagement {
	private static List<User> users;

	private static void load() {
		users = new ArrayList<User>();
		try {
			List<String[]> list = new CSVReader(new FileReader("users.csv"))
					.readAll();

			for (String[] line : list) {
				if (Integer.parseInt(line[0]) == 0) {
					users.add(new Student(line[1], line[2]));
				} else {
					users.add(new Lecturer(line[1], line[2]));
				}
			}
		} catch (FileNotFoundException e) {
			users.add(new Student("Student_1", "new"));
			users.add(new Student("Student_2", "new"));
			users.add(new Lecturer("Prof", "new"));
		} catch (IOException e) {
		}
	}

	private void save() {
		synchronized (users) {
			try {
				CSVWriter writer = new CSVWriter(new FileWriter("users.csv"));
				for (User user : users) {
					String type = "0";
					if (user instanceof Lecturer) {
						type = "1";
					}
					String[] entries = { type, user.getName(),
							user.getPassword() };
					writer.writeNext(entries);
				}
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public UserManagement() {
		if (users == null) {
			load();
		}
	}

	/**
	 * login and return the loggein user, or null
	 * @param user
	 * @param password
	 * @return
	 */
	public User login(String user, String password) {
		synchronized (users) {
			for (User u : users) {
				if (u.getName().equals(user)
						&& u.getPassword().equals(password)) {
					return u;
				}
			}
		}
		return null;
	}
	
	/**
	 * register a new user
	 * @param user
	 */
	public void registerUser(User user){
		users.add(user);
		save();
	}
}
